﻿ #region Disclaimer/Info
 
 /////////////////////////////////////////////////////////////////////////////////////////////////
 //
 //   File:		PagerHelper.cs
 //   Website:		http://dexterblogengine.com/
 //   Authors:		http://dexterblogengine.com/About.ashx
 //   Rev:		1
 //   Created:		19/01/2011
 //   Last edit:		19/01/2011
 //   License:		GNU Library General Public License (LGPL)
 // 
 //   For updated news and information please visit http://dexterblogengine.com/
 //   Dexter is hosted to Codeplex at http://dexterblogengine.codeplex.com
 //   For any question contact info@dexterblogengine.com
 //
 ///////////////////////////////////////////////////////////////////////////////////////////////////
 
 #endregion

using System;
using System.Text;
using System.Web.Mvc;
using Dexter.Dependency;
using Dexter.Domain.Results;
using Dexter.Services;

namespace Dexter.Web.Mvc.Helpers {
	public static class PagerHelper {
		public static MvcHtmlString Pager<T> ( this HtmlHelper helper, IPagedResult<T> data ) {
			if ( data == null || data.TotalPages < 2 ) {
				return MvcHtmlString.Empty;
			}

			var u = DexterContainer.Resolve<IUrlBuilder> ( );

			StringBuilder sb = new StringBuilder ( );
			sb.Append ( "<div class=\"pager\"><div class=\"pnavigation\">" );

			int seed = data.PageIndex % data.PageSize == 0 ? data.PageIndex : data.PageIndex - ( data.PageIndex % data.PageSize );

			if (data.PageIndex > 0)
				sb.AppendLine ( String.Format ( "<a href=\"{0}\">Previous</a>", u.SetPageToUrl ( data.PageIndex, helper.ViewContext ) ) );

			if (data.PageIndex - data.PageSize >= 0)
				sb.AppendLine ( String.Format ( "<a href=\"{0}\">...</a>", u.SetPageToUrl ( ( data.PageIndex - data.PageSize ) + 1, helper.ViewContext ) ) );

			for (int i = seed; i < Math.Ceiling ( data.TotalCount / 10d  ) && i < seed + data.PageSize; i++) {
				if (i == data.PageIndex) {
					sb.AppendFormat ( "<span class=\"current\">&#8201;{0}&#8201;</span>", i + 1 );
				}
				else {
					sb.AppendLine ( String.Format ( "<a href=\"{0}\">{1}</a>", u.SetPageToUrl ( i + 1, helper.ViewContext ), i + 1 ) );
				}
			}

			if (data.PageIndex + data.PageSize <= ( Math.Ceiling ( data.TotalCount / 10d ) - 1 ))
				sb.AppendLine ( String.Format ( "<a href=\"{0}\">...</a>" , u.SetPageToUrl ( ( data.PageIndex + data.PageSize ) + 1 , helper.ViewContext ) ) );

			if (data.PageIndex < ( Math.Ceiling ( data.TotalCount / 10d ) - 1 ))
				sb.AppendLine ( String.Format ( "<a href=\"{0}\">Next</a>",  u.SetPageToUrl (data.PageIndex + 2, helper.ViewContext )) );

			sb.Append ( "</div></div>" );

			return MvcHtmlString.Create ( sb.ToString ( ) );
		}
	}
}
